package com.csh.wx.controller;

import com.csh.wx.handler.WxChatMsgFactory;
import com.csh.wx.handler.WxChatMsgHandler;
import com.csh.wx.utils.MessageUtil;
import com.csh.wx.utils.SHA1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;


@RestController
@RequestMapping("/wx")
@Slf4j
public class CallBackController {

    private static final String token = "woshiwangfuchaodebaba";

    @Resource
    private WxChatMsgFactory wxChatMsgFactory;

    @RequestMapping("/test")
    public String test() {
        return "hello world";
    }

    /**
     * 回调消息校验，验证消息的确来自微信服务器
     */
    @GetMapping("/callback")
    public String callback(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr) {
        log.info("get验签请求参数：signature:{}，timestamp:{}，nonce:{}，echostr:{}",
                signature, timestamp, nonce, echostr);
        String shaStr = SHA1.getSHA1(token, timestamp, nonce, "");
        if (signature.equals(shaStr)){
            return echostr;
        }
        return "unknown";
    }

    //微信传过来文本消息是xml格式的，所有加上produces = "application/xml;charset=UTF-8
    //如果设置文本消息加密的话，就需要用到msgSignature这个参数了，目前用的明文
    @PostMapping(value = "callback", produces = "application/xml;charset=UTF-8")
    public String callback(
            @RequestBody String requestBody,
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam(value = "msg_signature", required = false) String msgSignature) {
        log.info("接收到微信消息：requestBody：{}", requestBody);

        //解析微信传过来的xml消息为Map集合格式，获取MsgType、Event对应的内容
        //文本消息中为MsgType(text)与Content(内容)，关注或取关事件消息中为MsgType(event)与Event(关注或取关)
        Map<String, String> messageMap = MessageUtil.parseXml(requestBody);
        String msgType = messageMap.get("MsgType");
        String event = messageMap.get("Event") == null ? "" : messageMap.get("Event");
        log.info("msgType:{},event:{}", msgType, event);

        StringBuilder sb = new StringBuilder();
        sb.append(msgType);
        if (!StringUtils.isEmpty(event)) {
            sb.append(".");
            sb.append(event);
        }
        String msgTypeKey = sb.toString();
        WxChatMsgHandler wxChatMsgHandler = wxChatMsgFactory.getHandlerByMsgType(msgTypeKey);
        //如果用户的操作类型是枚举中没有定义的，则返回unknown
        if (Objects.isNull(wxChatMsgHandler)) {
            return "unknown";
        }
        String replyContent = wxChatMsgHandler.dealMsg(messageMap);
        log.info("replyContent:{}", replyContent);
        return replyContent;
    }

//    接收到微信消息：requestBody：
//    <xml>
//    <ToUserName><![CDATA[gh_aae37cdf4c09]]></ToUserName>
//    <FromUserName><![CDATA[oNE1r62XNsGO3aJJoRGvg-cuA2jw]]></FromUserName>
//    <CreateTime>1712753609</CreateTime>
//    <MsgType><![CDATA[text]]></MsgType>
//    <Content><![CDATA[验证码]]></Content>
//    <MsgId>24520732838909442</MsgId>
//    </xml>

//    接收到微信消息：requestBody：
//    <xml>
//    <ToUserName><![CDATA[gh_aae37cdf4c09]]></ToUserName>
//    <FromUserName><![CDATA[oNE1r62XNsGO3aJJoRGvg-cuA2jw]]></FromUserName>
//    <CreateTime>1712755489</CreateTime>
//    <MsgType><![CDATA[event]]></MsgType>
//    <Event><![CDATA[subscribe]]></Event>
//    <EventKey><![CDATA[]]></EventKey>
//    </xml>
}



